package com.uchedao.seller.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.uchedao.seller.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageUtils {

    private static final DisplayImageOptions defaultOption = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.alert_bg_blur_all)
            .showImageForEmptyUri(R.drawable.alert_bg_blur_all)
            .showImageOnFail(R.drawable.alert_bg_blur_all).cacheInMemory(true)
            .cacheOnDisk(true).considerExifParams(true).build();

    /**
     * 加载图片
     *
     * @param imageUrl
     * @param imageView
     */
    public static void loadImage(String imageUrl, ImageView imageView) {
        ImageLoader.getInstance().displayImage(imageUrl, imageView,
                defaultOption);
    }


    public static void loadImage(String url, ImageView iv, int defaultImageId) {
        ImageLoader il = ImageLoader.getInstance();
        DisplayImageOptions op = new DisplayImageOptions.Builder()
                .showImageOnLoading(defaultImageId)
                .showImageForEmptyUri(defaultImageId)
                .showImageOnFail(defaultImageId)
                .displayer(new FadeInBitmapDisplayer(200))    //设置加载完成时的显示动画
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .build();
        try {
            il.displayImage(url, iv, op);
        } catch (Exception e) {
            e.printStackTrace();
        } catch (OutOfMemoryError out) {

        }
    }

    /**
     * 加载图片
     *
     * @param imageUrl  图片地址
     * @param imageView
     * @param option    加载选项配置
     */
    public static void loadImage(String imageUrl, ImageView imageView,
                                 DisplayImageOptions option) {
        ImageLoader.getInstance().displayImage(imageUrl, imageView, option);
    }

    /**
     * 获取
     *
     * @return
     */

    public static DisplayImageOptions.Builder getDefaultImageOptionBuilder(
            int defaultImageRes) {
        DisplayImageOptions.Builder op = new DisplayImageOptions.Builder()
                .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true)
                .showImageForEmptyUri(defaultImageRes)
                .showImageOnFail(defaultImageRes)
                .showImageOnLoading(defaultImageRes);
        return op;
    }

    public static DisplayImageOptions.Builder getDefaultImageOptionBuilder() {
        DisplayImageOptions.Builder op = new DisplayImageOptions.Builder()
                .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true);
        return op;
    }

    /**
     * 清除图片缓存
     */
    public static void clearCache() {
        ImageLoader il = ImageLoader.getInstance();
        il.clearDiskCache();
        il.clearMemoryCache();
    }


    /**
     * 　　* 将bitmap转换成base64字符串
     * 　　*
     * 　　* @param bitmap
     * 　　* @return base64 字符串
     */
    public static String bitmaptoString(Context context, Uri uri, int size) throws IOException {
        // 将Bitmap转换成字符串
        Bitmap bitmap = getThumbnail(context, uri, size);
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bStream);
        byte[] bytes = bStream.toByteArray();
        String string = Base64.encodeToString(bytes, Base64.DEFAULT);
        bitmap.recycle();
        return string;
    }

    /**
     * 　　* 将bitmap转换成base64字符串
     * 　　*
     * 　　* @param bitmap
     * 　　* @return base64 字符串
     */
    public static String bitmapToString(Bitmap bitmap, int bitmapQuality) {
        String ret = "";
        // 将Bitmap转换成字符串
        if (bitmap != null) {
            ByteArrayOutputStream bStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, bitmapQuality, bStream);
            byte[] bytes = bStream.toByteArray();
            ret = Base64.encodeToString(bytes, Base64.DEFAULT);
        }
        return ret;
    }

    /**
     * 保存方法
     */
    public static String saveBitmap(Context cxt, Bitmap bm, String name) {
        String path;
        File cache = cxt.getCacheDir();
        File f = new File(cache, name);
        if (f.exists()) {
            f.delete();
        }
        path = f.getPath();
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Log.i("QRImage", "已经保存 >>>>>" + path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }


    public static Bitmap getThumbnail(Context context, Uri uri, int size) throws FileNotFoundException, IOException {
        InputStream input = context.getContentResolver().openInputStream(uri);
        BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
        onlyBoundsOptions.inJustDecodeBounds = true;
        onlyBoundsOptions.inDither = true;//optional
        onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
        input.close();
        if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
            return null;
        int originalSize = onlyBoundsOptions.outWidth;
        double ratio = (originalSize > size) ? (originalSize / size) : 1.0;
        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
        bitmapOptions.inDither = true;//optional
        bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        input = context.getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
        input.close();
        return bitmap;
    }

    private static int getPowerOfTwoForSampleRatio(double ratio) {
        int k = Integer.highestOneBit((int) Math.floor(ratio));
        if (k == 0) return 1;
        else return k;
    }
}
